<template>
  <a-form layout="horizontal" :model="form" :rules="rules" @keyup.enter="handleSubmit">
    <a-form-item field="userAccount" validate-trigger="blur" hide-label>
      <a-input v-model="form.userAccount" style="height: 40px" placeholder="请输入用户名">
        <template #prefix>
          <icon-user />
        </template>
      </a-input>
    </a-form-item>
    <a-form-item field="userPassword" validate-trigger="blur" hide-label>
      <a-input-password
        v-model="form.userPassword"
        style="height: 40px"
        placeholder="请输入密码"
        allow-clear
      >
        <template #prefix>
          <icon-lock />
        </template>
      </a-input-password>
    </a-form-item>
    <a-button
      type="primary"
      style="margin: 32px 0 6px"
      long
      :loading="loading"
      @click="handleSubmit"
    >
      登录
    </a-button>
  </a-form>
</template>

<script lang="ts" setup>
import { reactive, ref } from 'vue'
import { userLoginUsingPost } from '@/api/userController.ts'
import { useLoginUserStore } from '@/stores/useLoginUserStore.ts'
import { Message } from '@arco-design/web-vue'
import { useRouter } from 'vue-router'

const loading = ref(false)

const form = reactive({
  userAccount: '',
  userPassword: '',
} as API.UserLoginRequest)

const router = useRouter()
const loginUserStore = useLoginUserStore()

const rules = {
  userAccount: [{ required: true, message: '请输入账号' }],
  userPassword: [{ required: true, message: '请输入密码' }],
}

const handleSubmit = async () => {
  loading.value = true
  const res = await userLoginUsingPost(form)
  if (res.data.code === 0) {
    await loginUserStore.fetchLoginUser()
    Message.success('登录成功')
    router.push({
      path: '/',
      replace: true,
    })
  } else {
    Message.error('登录失败，' + res.data.message)
  }
  loading.value = false
}
</script>

<style scoped>
.login-form-actions {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  margin-top: 24px;
  margin-bottom: 6px;
}

.login-form-more {
  justify-content: center;
}

.login-form-more .arco-icon {
  font-size: 20px;
  cursor: pointer;
  transition: transform 0.2s ease;
}

.login-form-more .arco-icon:hover {
  transform: scale(1.3);
}
</style>
